package socket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class Server5 {
    private ServerSocket serverSocket;

    private List<PrintWriter> allOut = new ArrayList<>();

    public Server5(){
        System.out.println("正在启动服务器....");
        try {
            serverSocket = new ServerSocket(8088);
            System.out.println("服务器启动完毕！");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start()  {
        try {
            while (true){
                System.out.println("等待客户端连接....");
                Socket socket = serverSocket.accept();
                System.out.println("一个客户端已经连接!");
                ClientHandler clientHandler = new ClientHandler(socket);
                Thread t = new Thread(clientHandler);
                t.start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Server5 server5 = new Server5();
        server5.start();
    }

    private class ClientHandler implements Runnable{
        private Socket socket;
        private String host;
        public ClientHandler(Socket socket){
            this.socket = socket;
            host = socket.getInetAddress().getHostAddress();
        }

        public void run(){
            PrintWriter pw;
            try {
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(
                                socket.getInputStream()
                        )
                );
                pw = new PrintWriter(
                        new BufferedWriter(
                                new OutputStreamWriter(
                                        socket.getOutputStream(),"UTF-8"
                                )
                        ),true
                );
                synchronized (allOut){
                    allOut.add(pw);
                    System.out.println(host+"上线了，当前在线人数："+allOut.size());
                }
                sendMessage(host+"上线了,当前在线人数："+allOut.size());
                String message;
                while ((message = br.readLine()) != null){
                    System.out.println(host+"说："+message);
                    sendMessage(host+"说："+message);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                //线程对应的客户端断开连接之后，while循环结束，需要把响应客户端的输出流移出集合
                //避免再次广播发送消息给客户端
                synchronized (allOut){
                    Iterator<PrintWriter> iterator = allOut.iterator();
                    while (iterator.hasNext()){
                        iterator.next();
                        iterator.remove();
                    }
                }
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        private void sendMessage(String message){
            synchronized (allOut){
                for (PrintWriter pw : allOut){
                    pw.println(message);
                }
            }

        }
    }
}
